package com.tistory.transfer.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.tistory.admin.common.SessionManager;
import com.tistory.common.vo.CommonReq;
import com.tistory.commons.utils.DateUtil;
import com.tistory.commons.utils.ExcelVo;
import com.tistory.commons.utils.FileUploadUtil;
import com.tistory.commons.utils.StringUtil;
import com.tistory.commons.utils.XlsReadBank;
import com.tistory.commons.utils.XlsReadCard;
import com.tistory.commons.utils.XlsReadRealBank;
import com.tistory.commons.utils.XlsReadRealCard;
import com.tistory.commons.utils.XlsxReadBank;
import com.tistory.commons.utils.XlsxReadCard;
import com.tistory.commons.utils.XlsxReadRealBank;
import com.tistory.commons.utils.XlsxReadRealCard;
import com.tistory.credit.service.CreditService;
import com.tistory.credit.vo.CreditReq;
import com.tistory.credit.vo.CreditRes;
import com.tistory.login.service.LoginService;
import com.tistory.login.vo.MemberSearchInfo;

@Controller
public class TransferController {

	private static final Logger log = LoggerFactory.getLogger(TransferController.class);

	@Autowired
	private CreditService creditService;

	@Autowired
	private LoginService loginService;


	@RequestMapping(value="transfer/minusSearch.do")
	public ModelAndView minusSearch(HttpServletRequest request , CommonReq req) throws SQLException{
		ModelAndView modelAndView = new ModelAndView();

		setReqParamValue(req);

		List<CreditReq>minusSearchList = creditService.getMinusPayList(req);
		Integer totalCount = creditService.getCreditMainListCount(req);
		req.setTotalCount(totalCount);
		modelAndView.addObject("minusSearchList", minusSearchList);
		modelAndView.addObject("model", req);
		modelAndView.addObject("today", DateUtil.getSysDate("yyyy-MM-dd"));
		modelAndView.setViewName("transfer/minusSearch");

		// 권한체크
		modelAndView = SessionManager.init(request,modelAndView);
		return modelAndView;

	}	

	@RequestMapping(value="transfer/minusPayList.do")
	public ModelAndView minusPayList(HttpServletRequest request, CommonReq req) throws SQLException{

		ModelAndView modelAndView = new ModelAndView();

		setReqParamValue(req);

		List<CreditReq>minusPayList = creditService.getMinusPayList(req);
		Integer totalCount = creditService.getCreditMainListCount(req);
		req.setTotalCount(totalCount);
		modelAndView.addObject("minusPayList", minusPayList);
		modelAndView.addObject("model", req);
		modelAndView.addObject("today", DateUtil.getSysDate("yyyy-MM-dd"));

		nvlStartEndDate(req);
		modelAndView.setViewName("transfer/minusPayList");

		// 권한체크
		modelAndView = SessionManager.init(request,modelAndView);
		return modelAndView;
	}		

	@RequestMapping(value="transfer/overProcess.do")
	public ModelAndView overProcess(HttpServletRequest request, CommonReq req) throws SQLException{

		ModelAndView modelAndView = new ModelAndView();


		modelAndView.addObject("model", req);
		nvlStartEndDate(req);
		modelAndView.setViewName("transfer/overProcess");

		// 권한체크
		modelAndView = SessionManager.init(request,modelAndView);
		return modelAndView;
	}		
	@RequestMapping(value="transfer/payProcess.do")
	public ModelAndView payProcess(HttpServletRequest request, CommonReq req) throws SQLException, UnsupportedEncodingException{
		request.setCharacterEncoding("UTF-8");
		ModelAndView modelAndView = new ModelAndView();

		setReqParamValue(req);

		List<CreditReq> payProcessList = creditService.getPayProcessList(req);
		Integer totalCount = creditService.getCreditMainListCount(req);
		req.setTotalCount(totalCount);
		modelAndView.addObject("payProcessList", payProcessList);
		modelAndView.addObject("model", req);
		modelAndView.addObject("today", DateUtil.getSysDate("yyyy-MM-dd"));

		nvlStartEndDate(req);
		modelAndView.setViewName("transfer/payProcess");

		// 권한체크
		modelAndView = SessionManager.init(request,modelAndView);
		return modelAndView;
	}		


	// 지급 금액 등록
	@RequestMapping(value="transfer/ajaxInsertPay.do", method=RequestMethod.POST)
	public @ResponseBody String ajaxInsertPay(@RequestParam Map<String,Object> map, HttpServletResponse response, HttpServletRequest request) throws SQLException, UnsupportedEncodingException{
		// 권한체크
		SessionManager.funInit(request);
		String result ="success";
		try {
			creditService.insertPay(map);
		} catch (Exception e) {
			e.printStackTrace();
			result = "fail";
			return result;
		}
		return result;
	}		

	@RequestMapping(value="transfer/bankList.do")
	public ModelAndView bankList(HttpServletRequest request, CommonReq req) throws SQLException, UnsupportedEncodingException{
		request.setCharacterEncoding("UTF-8");
		ModelAndView modelAndView = new ModelAndView();

		setReqParamValue(req);

		List<CreditRes> creditMainList = creditService.getCreditMainList(req);
		Integer totalCount = creditService.getCreditMainListCount(req);
		req.setTotalCount(totalCount);
		modelAndView.addObject("creditMainList", creditMainList);
		modelAndView.addObject("model", req);
		modelAndView.addObject("today", DateUtil.getSysDate("yyyy-MM-dd"));

		nvlStartEndDate(req);
		modelAndView.setViewName("transfer/bankList");

		// 권한체크
		modelAndView = SessionManager.init(request,modelAndView);
		return modelAndView;
	}			

	// 엑셀 파일 Parsing ajax 통신 -- 카드사 매출 처리
	@RequestMapping(value="transfer/ajaxBankUploadFile.do", method=RequestMethod.POST)
	public @ResponseBody String ajaxBankUploadFile(HttpServletResponse response, MultipartHttpServletRequest request) throws Exception{
		// 권한체크
		SessionManager.funInit(request);
		Iterator<String> itr = request.getFileNames();
		//		MultipartFile muntiFile = request.getFile(itr.next());

		String result ="success";

		String today = DateUtil.getSysDate();
		String userId = request.getParameter("userId");
		String originFileName = "";;
		String uploadPath ="/upload/"+today+"/";
		File dir = new File(uploadPath);
		if(!dir.exists()){
			dir.mkdirs();
		}


		if(itr.hasNext()) {
			MultipartFile mpf = request.getFile(itr.next());
			originFileName = mpf.getOriginalFilename();
			originFileName= new String(originFileName.getBytes("8859_1"),"utf-8");
			String fullPath =uploadPath+originFileName;
			File f = new File(fullPath);
			// 파일 업로드 처리 완료.
			mpf.transferTo(f);

			File file = new File(fullPath);
			String saveUploadPath ="/project/spring_ibatis/WebContent/upload/excel/bank/"+today;	    
			String uploadFullPath = FileUploadUtil.uploadFile(file, saveUploadPath, originFileName); // 실제 파일 업로드 경로
			int pos =  originFileName.lastIndexOf( "." );
			String ext =  originFileName.substring( pos + 1 );
			//실제 디플로이되는 폴더의 root path를 따온다
			List<CreditReq>creditList = new ArrayList<CreditReq>();
			if(ext.equals("xlsx")){
				creditList = XlsxReadBank.parsingExcel(uploadFullPath,userId);	// 엑셀 파싱 
			}else{
				creditList = XlsReadBank.parsingExcel(uploadFullPath,userId);	// 엑셀 파싱 
			}			
			if(creditList.size() ==0 ){
				result = "fail";
			}
			creditService.insertCreditInfo(creditList);

		} else {
			result ="fail";
		}


		return result;
	}	

	@RequestMapping(value="transfer/cardList.do")
	public ModelAndView cardList(HttpServletRequest request, CommonReq req) throws SQLException, UnsupportedEncodingException{
		request.setCharacterEncoding("UTF-8");
		ModelAndView modelAndView = new ModelAndView();


		setReqParamValue(req);

		List<CreditRes> creditMainList = creditService.getCreditMainList(req);
		Integer totalCount = creditService.getCreditMainListCount(req);
		req.setTotalCount(totalCount);
		modelAndView.addObject("creditMainList", creditMainList);
		modelAndView.addObject("model", req);
		modelAndView.addObject("today", DateUtil.getSysDate("yyyy-MM-dd"));

		nvlStartEndDate(req);
		modelAndView.setViewName("transfer/cardList");

		// 권한체크
		modelAndView = SessionManager.init(request,modelAndView);

		return modelAndView;
	}			

	// 엑셀 파일 Parsing ajax 통신 -- 카드사 입금 처리
	@RequestMapping(value="transfer/ajaxCardUploadFile.do", method=RequestMethod.POST)
	public @ResponseBody String ajaxCardUploadFile(HttpServletResponse response, MultipartHttpServletRequest request) throws Exception{
		// 권한체크
		SessionManager.funInit(request);
		Iterator<String> itr = request.getFileNames();
		//		MultipartFile muntiFile = request.getFile(itr.next());

		String result ="success";

		String today = DateUtil.getSysDate();
		String userId = request.getParameter("userId");
		String originFileName = "";;
		String uploadPath ="/upload/"+today+"/";
		File dir = new File(uploadPath);
		if(!dir.exists()){
			dir.mkdirs();
		}


		if(itr.hasNext()) {
			MultipartFile mpf = request.getFile(itr.next());
			originFileName = mpf.getOriginalFilename();
			originFileName= new String(originFileName.getBytes("8859_1"),"utf-8");
			String fullPath =uploadPath+originFileName;

			File f = new File(fullPath);
			// 파일 업로드 처리 완료.
			mpf.transferTo(f);

			File file = new File(fullPath);
			String saveUploadPath ="/project/spring_ibatis/WebContent/upload/excel/card/"+today;	    
			String uploadFullPath = FileUploadUtil.uploadFile(file, saveUploadPath, originFileName); // 실제 파일 업로드 경로

			int pos =  originFileName.lastIndexOf( "." );
			String ext =  originFileName.substring( pos + 1 );
			//실제 디플로이되는 폴더의 root path를 따온다
			List<CreditReq>creditList = new ArrayList<CreditReq>();
			if(ext.equals("xlsx")){
				creditList = XlsxReadCard.parsingExcel(uploadFullPath,userId);	// 엑셀 파싱 
			}else{
				creditList = XlsReadCard.parsingExcel(uploadFullPath,userId);	// 엑셀 파싱 
			}			
			if(creditList.size() ==0 ){
				result = "fail";
			}
			creditService.insertCreditCardInfo(creditList);				

		} else {
			result ="fail";
		}



		return result;
	}		

	@RequestMapping(value="transfer/realCardList.do")
	public ModelAndView realCardList(HttpServletRequest request, CommonReq req) throws SQLException, UnsupportedEncodingException{
		request.setCharacterEncoding("UTF-8");
		ModelAndView modelAndView = new ModelAndView();

		setReqParamValue(req);

		List<CreditRes> creditMainList = creditService.getCreditMainList(req);
		Integer totalCount = creditService.getCreditMainListCount(req);
		req.setTotalCount(totalCount);
		modelAndView.addObject("creditMainList", creditMainList);
		modelAndView.addObject("model", req);
		modelAndView.addObject("today", DateUtil.getSysDate("yyyy-MM-dd"));

		nvlStartEndDate(req);
		modelAndView.setViewName("transfer/realCardList");

		// 권한체크
		modelAndView = SessionManager.init(request,modelAndView);
		return modelAndView;
	}		

	@RequestMapping(value="transfer/realBankList.do")
	public ModelAndView realBankList(HttpServletRequest request, CommonReq req) throws SQLException, UnsupportedEncodingException{
		request.setCharacterEncoding("UTF-8");
		ModelAndView modelAndView = new ModelAndView();

		setReqParamValue(req);

		List<CreditRes>realBankList = creditService.getRealBankList(req);
		Integer totalCount = creditService.getCreditMainListCount(req);
		req.setTotalCount(totalCount);
		modelAndView.addObject("realBankList", realBankList);
		modelAndView.addObject("model", req);
		modelAndView.addObject("today", DateUtil.getSysDate("yyyy-MM-dd"));

		nvlStartEndDate(req);
		modelAndView.setViewName("transfer/realBankList");

		// 권한체크
		modelAndView = SessionManager.init(request,modelAndView);
		return modelAndView;
	}		


	// 엑셀 파일 Parsing ajax 통신 -- 카드사 실입금 처리
	@RequestMapping(value="transfer/ajaxRealCardUploadFile.do", method=RequestMethod.POST)
	public @ResponseBody String ajaxRealCardUploadFile(HttpServletResponse response, MultipartHttpServletRequest request) throws Exception{


		// 권한체크
		SessionManager.funInit(request);
		Iterator<String> itr = request.getFileNames();
		//		MultipartFile muntiFile = request.getFile(itr.next());

		String result ="success";

		String today = DateUtil.getSysDate();
		String userId = request.getParameter("userId");
		String reqDate = DateUtil.dashDate(request.getParameter("reqDate"));
		String originFileName = "";;
		String uploadPath ="/upload/"+today+"/";
		File dir = new File(uploadPath);
		if(!dir.exists()){
			dir.mkdirs();
		}

		if(itr.hasNext()) {
			MultipartFile mpf = request.getFile(itr.next());
			originFileName = mpf.getOriginalFilename();
			originFileName= new String(originFileName.getBytes("8859_1"),"utf-8");
			String fullPath =uploadPath+originFileName;

			File f = new File(fullPath);
			// 파일 업로드 처리 완료.
			mpf.transferTo(f);

			File file = new File(fullPath);
			String saveUploadPath ="/project/spring_ibatis/WebContent/upload/excel/realcard/"+today;	    
			String uploadFullPath = FileUploadUtil.uploadFile(file, saveUploadPath, originFileName); // 실제 파일 업로드 경로

			int pos =  originFileName.lastIndexOf( "." );
			String ext =  originFileName.substring( pos + 1 );
			//실제 디플로이되는 폴더의 root path를 따온다
			List<CreditReq>creditList = new ArrayList<CreditReq>();
			if(ext.equals("xlsx")){
				creditList = XlsxReadRealCard.parsingExcel(uploadFullPath,userId,reqDate);	// 엑셀 파싱 
			}else{
				creditList = XlsReadRealCard.parsingExcel(uploadFullPath,userId,reqDate);	// 엑셀 파싱 
			}			
			if(creditList.size() ==0 ){
				result = "fail";
			}
			creditService.insertCreditRealCardInfo(creditList);

		} else {
			result ="fail";
		}
		return result;
	}	


	// 엑셀 파일 Parsing ajax 통신 -- 은행사 실입금 처리
	@RequestMapping(value="transfer/ajaxRealBankUploadFile.do", method=RequestMethod.POST)
	public @ResponseBody String ajaxRealBankUploadFile(HttpServletResponse response, MultipartHttpServletRequest request) throws Exception{

		// 권한체크
		SessionManager.funInit(request);
		Iterator<String> itr = request.getFileNames();
		//				MultipartFile muntiFile = request.getFile(itr.next());

		String result ="success";

		String today = DateUtil.getSysDate();
		String userId = request.getParameter("userId");
		String reqDate = DateUtil.dashDate(request.getParameter("reqDate"));
		String payProdFee = request.getParameter("payProdFee");
		String originFileName = "";;
		String uploadPath ="/upload/"+today+"/";
		File dir = new File(uploadPath);
		if(!dir.exists()){
			dir.mkdirs();
		}

		if(itr.hasNext()) {
			MultipartFile mpf = request.getFile(itr.next());
			originFileName = mpf.getOriginalFilename();
			originFileName= new String(originFileName.getBytes("8859_1"),"utf-8");
			String fullPath =uploadPath+originFileName;

			File f = new File(fullPath);
			// 파일 업로드 처리 완료.
			mpf.transferTo(f);

			File file = new File(fullPath);
			String saveUploadPath ="/project/spring_ibatis/WebContent/upload/excel/realbank/"+today;	    
			String uploadFullPath = FileUploadUtil.uploadFile(file, saveUploadPath, originFileName); // 실제 파일 업로드 경로

			int pos =  originFileName.lastIndexOf( "." );
			String ext =  originFileName.substring( pos + 1 );
			//실제 디플로이되는 폴더의 root path를 따온다
			MemberSearchInfo searchInfo = new MemberSearchInfo();
			searchInfo = loginService.getMemberSearch(userId);

			List<CreditReq>creditList = new ArrayList<CreditReq>();
			if(ext.equals("xlsx")){
				creditList = XlsxReadRealBank.parsingExcel(uploadFullPath,userId,reqDate,searchInfo,payProdFee);	// 엑셀 파싱 
			}else{
				creditList = XlsReadRealBank.parsingExcel(uploadFullPath,userId,reqDate,searchInfo,payProdFee);	// 엑셀 파싱 
			}			

			if(creditList.size() ==0 ){
				result = "fail";
			}
			creditService.insertCreditRealBankInfo(creditList);

		} else {
			result ="fail";
		}

		return result;
	}	
	// 일짜별 데이터 삭제
	@RequestMapping(value="transfer/ajaxDeleteData.do", method=RequestMethod.POST)
	public @ResponseBody String ajaxDeleteData(@RequestParam Map<String,Object> map, HttpServletResponse response, HttpServletRequest request) throws SQLException, UnsupportedEncodingException{
		// 권한체크
		SessionManager.funInit(request);
		String result ="success";
		try {
			Integer kk = creditService.deleteCreditInfo(map);
			if (kk ==0){
				result ="success";
			}else{
				result ="good";
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = "fail";
			return result;
		}
		return result;
	}		

	@RequestMapping(value="transfer/minusExcel.do")
	public ModelAndView minusExcel(HttpServletRequest request, CommonReq req) throws SQLException, UnsupportedEncodingException{
		request.setCharacterEncoding("UTF-8");

		// create some sample data
		List<ExcelVo> listBooks = new ArrayList<ExcelVo>();
		listBooks.add(new ExcelVo("1", "2015-02-12  11:05:35 AM", "3071036112","14181113", 20));
		listBooks.add(new ExcelVo("2", "2015-02-12  11:05:35 AM","3071036112", "14181113", 20));
		//			listBooks.add(new Book("Java Generics and Collections","Philip Wadler", "0596527756", "Oct 24, 2006", 29.52F));
		//			listBooks.add(new Book("Thinking in Java", "Bruce Eckel", "0596527756","February 20, 2006", 43.97F));
		//			listBooks.add(new Book("Spring in Action", "Craig Walls", "1935182358","June 29, 2011", 31.98F));

		return new ModelAndView("excelView", "listBooks", listBooks);
	}					



	private void nvlStartEndDate(CommonReq req){
		if(StringUtil.isEmpty(req.getSearchStRegDt()) || StringUtil.isEmpty(req.getSearchEdRegDt())) {
			try {
				req.setSearchStRegDt(DateUtil.dashDate(StringUtil.nvlStr(req.getSearchStRegDt(),DateUtil.getAddDay(-1, "yyyy-MM-dd"))));
				req.setSearchEdRegDt(DateUtil.dashDate(StringUtil.nvlStr(req.getSearchEdRegDt(),DateUtil.getSysDate("yyyy-MM-dd"))));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	};

	private CommonReq setReqParamValue(CommonReq req){
		int listCount = 10;		
		req.setStartRow(listCount * (req.getPage()-1)) ;
		req.setEndRow(listCount);


		return req;
	}

}
